import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const foodStore = createSlice({
    name: 'food',
    initialState: {
        //食品列表
        foodList: [],
        //菜单激活下标
        activeIndex: 0,
        //购物车列表
        cartList: [],


    },
    reducers: {
        //更改商品列表
        setFoodList(state, action) {
            state.foodList = action.payload
        },
        //更改activIndex
        changActiveIndex(state, action) {
            state.activeIndex = action.payload
        },
        //添加商品到购物车
        addCarList(state, action) {
            //是否添加过？以action.payload.id去carlist中匹配 匹配到了 添加过
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++

            } else {
                state.cartList.push(action.payload)
            }
        },
        //count增
        increCount(state, action) {
           const item= state.cartList.find(item=>item.id===action.payload.id)
           item.count++

        },
        //count减
        decreCount(state, action) {
            const item= state.cartList.find(item=>item.id===action.payload.id)
            if(item.count===0){
                return 
            }
            item.count--
 
         },
         //清空购物车
         clearCart(state,action){
            state.cartList=[]
         }
    }
})
const { setFoodList, changActiveIndex, addCarList,increCount,decreCount,clearCart } = foodStore.actions
//异步发请求获取数据方法
const fetchFoodList = () => {
    return async (dispatch) => {
        //编写异步逻辑
        const res = await axios.get('http://localhost:3004/takeaway')
        //调用dispatch函数提交action
        dispatch(setFoodList(res.data))

    }
}

export { fetchFoodList, changActiveIndex, addCarList ,increCount,decreCount ,clearCart}
const reducer = foodStore.reducer
export default reducer